package com.laolang.shop.modules.member.logic.api.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.laolang.shop.modules.member.entity.MemberAddressTag;
import com.laolang.shop.modules.member.logic.api.MemberAddressTagApiLogic;
import com.laolang.shop.modules.member.mappperstruct.MemberAddressTagMapperStruct;
import com.laolang.shop.modules.member.pojo.vo.MemberAddressTagVo;
import com.laolang.shop.modules.member.service.MemberAddressTagService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


/**
 * @author khlbat
 * @version 1.0
 * @date 2020/11/1 20:46
 */
@Slf4j
@Service
public class MemberAddressTagApiLogicImpl implements MemberAddressTagApiLogic {

    @Autowired
    private MemberAddressTagService memberAddressTagService;

    @Autowired
    private MemberAddressTagMapperStruct memberAddressTagMapperStruct;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<MemberAddressTagVo> list() {
        List<MemberAddressTagVo> vos = null;
        try {
            String tagJson = stringRedisTemplate.opsForValue().get("member_address_tag");
            if (StrUtil.isNotBlank(tagJson)) {
                vos = JSONUtil.toList(JSONUtil.parseArray(tagJson), MemberAddressTagVo.class);
                return vos;
            }
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
        }
        vos = memberAddressTagService.list().stream().map(memberAddressTag -> memberAddressTagMapperStruct.entity2vo(memberAddressTag)).collect(Collectors.toList());
        try {
            stringRedisTemplate.opsForValue().set("member_address_tag", JSONUtil.toJsonStr(vos));
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
        }
        return vos;
    }

    @Override
    public List<MemberAddressTagVo> query() {
        return memberAddressTagService.list().stream().map(memberAddressTag -> memberAddressTagMapperStruct.entity2vo(memberAddressTag)).collect(Collectors.toList());
    }

    @Override
    public Boolean add() {
        MemberAddressTag insert = new MemberAddressTag();
        insert.setUserId(1L);
        insert.setType(1);
        insert.setName("ceshi");
        return memberAddressTagService.save(insert);
    }

}
